package com.key.win.business.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.key.win.base.exception.BizException;
import com.key.win.base.page.MybatisPageServiceTemplate;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.business.chat.dao.ImFriendDao;
import com.key.win.business.chat.dao.ImFriendFullDao;
import com.key.win.business.chat.model.ImFriend;
import com.key.win.business.chat.service.ImFriendService;
import com.key.win.business.chat.vo.ImFriendFullVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class ImFriendServiceImpl extends ServiceImpl<ImFriendDao, ImFriend> implements ImFriendService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ImFriendFullDao imFriendFullDao;

    public PageResult<ImFriendFullVo> findFriendByPaged(PageRequest<ImFriend> t) {
        MybatisPageServiceTemplate<ImFriend, ImFriendFullVo> query = new MybatisPageServiceTemplate<ImFriend, ImFriendFullVo>(this.imFriendFullDao) {
            @Override
            protected AbstractWrapper constructWrapper(ImFriend friend) {
                return buildWrapper(friend);
            }

            @Override
            protected String constructNativeSql() {
                return "SELECT f.id, f.create_date, f.create_user_id, f.create_user_name, f.enable_flag, f.update_date, f.update_user_id, f.update_user_name, f.version, f.friend_Id, CASE WHEN f.`name` IS NOT NULL THEN f.`name` ELSE u.nick_name END AS `name`, f.groupId, g.`name` AS group_name, u.sign, u.head_img_url AS avatar FROM im_friends f LEFT JOIN im_group g ON f.groupId = g.id INNER JOIN sys_user u ON f.friend_Id = u.id";
            }
        };
        return query.doPagingQuery(t);
    }

    private AbstractWrapper buildWrapper(ImFriend imFriend) {
        if (imFriend == null) {
            logger.error("friend is null!");
            throw new BizException("好友为空！");
        }
        if (StringUtils.isBlank(imFriend.getUserId())) {
            logger.error("userId is null!");
            throw new BizException("当前用户为空！");
        }
        LambdaQueryWrapper<ImFriend> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(imFriend.getFriendId())) {
            lambdaQueryWrapper.eq(ImFriend::getFriendId, imFriend.getFriendId());
        }
        if (StringUtils.isNotBlank(imFriend.getGroupId())) {
            lambdaQueryWrapper.eq(ImFriend::getGroupId, imFriend.getGroupId());
        }
        lambdaQueryWrapper.eq(ImFriend::getUserId, imFriend.getUserId());
        return lambdaQueryWrapper;
    }

    public List<ImFriend> findFriend(ImFriend imFriend) {
        return this.list(this.buildWrapper(imFriend));
    }

    public boolean addFriend(ImFriend main) {
        if (main == null) {
            logger.error("friend is null!");
            throw new BizException("好友为空！");
        }
        if (StringUtils.isBlank(main.getFriendId())) {
            logger.error("friendId is null!");
            throw new BizException("好友为空！");
        }
        if (StringUtils.isBlank(main.getUserId())) {
            logger.error("userId is null!");
            throw new BizException("当前用户为空！");
        }
        List<ImFriend> imFriends = this.findFriend(main);
        if (!CollectionUtils.isEmpty(imFriends)) {
            logger.error("好友[{}]已是添加过了", main.getFriendId());
            throw new BizException("重复添加好友！");
        }
        if (this.save(main)) {
            ImFriend friend = new ImFriend();
            friend.setFriendId(main.getUserId());
            friend.setUserId(main.getFriendId());
            return this.save(friend);
        }
        return false;
    }

    @Override
    public boolean updateFriend(ImFriend imFriend) {
        if (imFriend == null) {
            logger.error("friend is null!");
            throw new BizException("好友为空！");
        }
        if (StringUtils.isBlank(imFriend.getId())) {
            logger.error("friend Id is null!");
            throw new BizException("好友为空！");
        }
        ImFriend dbImFriend = this.getById(imFriend.getId());
        if (dbImFriend == null) {
            logger.error("没有找到id[]的好友信息！", imFriend.getId());
            throw new BizException("好友不存在！");
        }
        dbImFriend.setName(imFriend.getName());
        dbImFriend.setGroupId(imFriend.getGroupId());
        return this.saveOrUpdate(dbImFriend);
    }

    public List<ImFriendFullVo> findFriendByUserId(String userId) {
        ImFriend f = new ImFriend();
        f.setUserId(userId);
        return imFriendFullDao.findMyFriend(this.buildWrapper(f));
    }

    @Override
    public boolean deleteFriend(String id) {
        if (StringUtils.isBlank(id)) {
            logger.error("delete user Id is null!");
            throw new BizException("Id为空！");
        }
        ImFriend byId = this.getById(id);
        if (byId == null) {
            logger.error("没有找到id[]的好友信息！", id);
            throw new BizException("好友不存在！");
        }
        if (this.removeById(id)) {
            ImFriend imFriend = new ImFriend();
            imFriend.setUserId(byId.getFriendId());
            imFriend.setFriendId(byId.getUserId());
            List<ImFriend> friends = this.findFriend(imFriend);
            if (CollectionUtils.isEmpty(friends)) {
                ImFriend friend = friends.get(0);
                return this.removeById(friend);
            }
        }
        return false;
    }
}
